package com.qf.common.event.consumer;

import com.qf.common.event.utils.EventMessage;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * 实际接收RabbitMQ队列消息的处理类
 */
@Component
public class RabbitMqListener {

    @Autowired
    private List<IEventHandler> eventHandlers;

    /**
     * 注入Spring中的线程池
     */
    @Autowired
    private Executor executor;

    /**
     * 监听对应的队列中的消息
     */
    @RabbitListener(queues = "queue-${spring.application.name}")
    public void rabbitMsgHandler(Message message){

        try {
            //解析Message 获得 eventMessage
            EventMessage eventMessage = (EventMessage) SerializationUtils.deserialize(message.getBody());

            //循环开发者定义的所有EventHandler实现类，逐个匹配事件类型
            for (IEventHandler eventHandler : eventHandlers) {
                //获取开发者自行定义的IEventHandler对象上的注解
                EventType eventType = eventHandler.getClass().getAnnotation(EventType.class);

                //将事件执行体放入runable的run方法中
                Runnable runnable = () -> {
                    //如果没有获取到EventType注解则直接不处理
                    //判断事件类型，如果类型不相同，则直接不处理
                    if (eventType == null || !eventType.type().equals(eventMessage.getEventType())) return;
                    //自定义的消息处理
                    eventHandler.eventHandler(eventMessage.getEvent());
                };

                if (eventType.isAsync()) {
                    //异步处理事件
                    executor.execute(runnable);
                } else {
                    //同步处理事件
                    runnable.run();
                }
            }
        } catch (Exception e){
        }
    }
}
